package com.zz.inventory.config;

import com.zz.inventory.domain.Classes;
import com.zz.inventory.domain.Students;
import com.zz.inventory.service.IClassesService;
import com.zz.inventory.service.IStudentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
// RedisCacheInitializer类的作用是在应用启动时预热Redis缓存。
public class RedisCacheInitializer implements CommandLineRunner {
    private static final int MAX_STUDENTS_TO_CACHE = 1000; // 限制缓存的学生数量

    @Autowired
    private IClassesService classesService;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private SchoolRedisService schoolRedisService;

    @Override
    public void run(String... args) {
        try {
            log.info("开始初始化Redis缓存...");
            long start = System.currentTimeMillis();

            // 并行缓存班级和学生
            CompletableFuture<Void> classFuture = CompletableFuture.runAsync(this::cacheAllClasses);
            CompletableFuture<Void> studentFuture = CompletableFuture.runAsync(this::cacheRecentStudents);

            CompletableFuture.allOf(classFuture, studentFuture).join();

            long duration = System.currentTimeMillis() - start;
            log.info("Redis缓存初始化完成，耗时{}ms", duration);
        } catch (Exception e) {
            log.error("Redis缓存初始化失败", e);
        }
    }

    private void cacheAllClasses() {
        try {
            List<Classes> allClasses = classesService.selectClassesList(new Classes());
            schoolRedisService.batchCacheClasses(allClasses);
            log.info("已缓存{}个班级", allClasses.size());
        } catch (Exception e) {
            log.error("班级缓存初始化异常", e);
        }
    }

    private void cacheRecentStudents() {
        try {
            Students query = new Students();
            query.setParams(Map.of(
                    "pageNum", 1,
                    "pageSize", MAX_STUDENTS_TO_CACHE,
                    "orderByColumn", "create_time",
                    "isAsc", "desc"
            ));

            List<Students> students = studentsService.selectStudentsList(query);
            schoolRedisService.batchCacheStudents(students);
            log.info("已缓存{}个学生", students.size());
        } catch (Exception e) {
            log.error("学生缓存初始化异常", e);
        }
    }
}